using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace EntityAop.Extensions
{
    public static class XmlSerializerHelper
    {
        public static String SerializeObject(Object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            xs.Serialize(xmlTextWriter, obj);

            memoryStream.Seek(0, SeekOrigin.Begin);

            return new StreamReader(memoryStream).ReadToEnd();
        }

        public static T DeserializeObject<T>(XmlTextReader xmlReader)
        {
            Type objType = typeof(T);

            object tempResult = new XmlSerializer(objType).Deserialize(xmlReader);

            if (tempResult is T)
            {
                return (T)tempResult;
            }

            return default(T);
        }

        public static T DeserializeObject<T>(string xml)
        {
            XmlTextReader xmlReader = new XmlTextReader(new StringReader(xml));

            return DeserializeObject<T>(xmlReader);
        }
    }
}